package dwetl.dwetl_example;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.jdbc.core.JdbcTemplate;

import dwetl.runner.EtlBuilder;

@SpringBootApplication
@ComponentScan({"dwetl"})
public class DwetlAppExample implements CommandLineRunner {
    @Autowired
    private EtlBuilder runner;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... args) throws Exception {
        long start=System.currentTimeMillis();
        runner.init("fact_exam.json");
        
        jdbcTemplate.execute(new ConnectionCallback<Boolean>() {
            @Override
            public Boolean doInConnection(Connection con) throws SQLException, DataAccessException {
                PreparedStatement pstmt=con.prepareStatement("select * from exam");
                ResultSet rs=pstmt.executeQuery();
                ResultSetMetaData mtd=rs.getMetaData();
                int cnt=mtd.getColumnCount();
                while(rs.next()){
                    Map<String, Object> map = new HashMap<>();
                    for(int i=1;i<=cnt;i++){
                        String key=mtd.getColumnName(i);
                        Object val=rs.getObject(key);
                        map.put(key, val);
                    }
                    runner.transform(map);
                }
                return true;
            }
        });

        long end=System.currentTimeMillis();
        System.out.println(end-start+" ms");
    }

    public static void main(String[] args) {
        SpringApplication.run(DwetlAppExample.class, args);
    }
}
